<?php

namespace Home\Controller;

class CartController extends BaseMemberController {

    function _initialize() {
        parent::_initialize();
        $this->_user_id = session('visitor.user_id');
        $this->_Cart_mod = M('cart');
    }

    /**
     * @api {get} /index.php?m=Home&c=Cart&a=get_cart_list 获取当前用户的购物车列表
     * 
     * @apiName 获取当前用户的购物车列表
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 获取当前用户的购物车列表
     * 
     * @apiSuccess {String} status.quantity 产品数量
     * @apiSuccess {String} status.amount 总金额
     * @apiSuccess {String} status.kinds 产品数
     * @apiSuccess {String} carts.amount 当前店铺消费金额
     * @apiSuccess {String} carts.quantity 当前店铺产品数量
     * @apiSuccess {String} carts.kinds 当前店铺产品数
     * @apiSuccess {String} carts.store_id 当前店铺ID
     * @apiSuccess {String} carts.store_name 当前店铺名称
     * @apiSuccess {String} carts.enable_free_fee 当前店铺是否开启免包邮
     * @apiSuccess {String} carts.amount_for_free_fee 免包邮金额
     * @apiSuccess {String} carts.acount_for_free_fee 免包邮数量
     * @apiSuccess {String} carts.items.rec_id 购物车ID
     * @apiSuccess {String} carts.items.user_id 购物车用户ID
     * @apiSuccess {String} carts.items.store_id 购物车店铺ID
     * @apiSuccess {String} carts.items.goods_id 购物车产品ID
     * @apiSuccess {String} carts.items.goods_name 购物车产品名称
     * @apiSuccess {String} carts.items.spec_id 购物车产品规格ID
     * @apiSuccess {String} carts.items.specification 购物车产品规格名称
     * @apiSuccess {String} carts.items.price 购物车产品价格
     * @apiSuccess {String} carts.items.quantity 购物车产品数量
     * @apiSuccess {String} carts.items.goods_image 购物车产品图片
     * @apiSuccess {String} carts.items.goods_old_price 购物车产品原始价格
     * @apiSuccess {String} carts.items.goods_type 购物车产品类别
     * @apiSuccess {String} carts.items.promotions_id 购物车产品促销ID
     * @apiSuccess {String} carts.items.store_name 购物车产品名称
     * @apiSuccess {String} carts.items.stock 购物车产品库存
     * @apiSuccess {String} carts.items.subtotal 购物车产品小计
     */
    function get_cart_list() {
        $cart_status = $this->_get_cart_status();
        render('10000', '', $cart_status);
    }

    /**
     * @api {get} /index.php?m=Home&c=Goods&a=drop 删除购物车内商品
     * 
     * @apiName 删除购物车内商品
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 删除购物车内商品
     * 
     * @apiParam {String} rec_id 购物车ID
     * 
     */
    function drop() {
        /* 传入rec_id，删除并返回购物车统计即可 */
        $rec_id = I('request.rec_id', 0);
        if (!$rec_id) {
            render('10001', '缺少参数');
        }

        $data['rec_id'] = $rec_id;
        $data['user_id'] = $this->_user_id;

        $cart_info = $this->_Cart_mod->where($data)->find();
        if ($cart_info) {
            $this->_Cart_mod->where($data)->delete();
        } else {
            render('10401', '购物车不存在此商品');
        }
        $cart_status = $this->_get_cart_status();
        render('10000', '', $cart_status);
    }

    /**
     * @api {get} /index.php?m=Home&c=Goods&a=add 把商品加入购物车
     * 
     * @apiName 把商品加入购物车
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 把商品加入购物车
     * 
     * @apiParam {String} gid 团购ID
     * @apiParam {String} spec_id 规格ID
     * @apiParam {String} quantity 数量
     */
    function add() {
        $promotions_id = I('request.gid', 0);
        $spec_id = I('request.spec_id', 0);
        $quantity = I('request.quantity', 0);
        if (!$spec_id || !$quantity) {
            render('10001', '缺少参数');
        }

        /* 是否有商品 */
        $Goodsspec_mod = M('goods_spec');
        $spec_info = $Goodsspec_mod
                ->field('g.store_id, g.if_open, g.goods_id, g.goods_name, g.spec_name_1, g.spec_name_2, g.spec_name_3, g.spec_name_4, g.default_image, gs.spec_id, gs.spec_1, gs.spec_2, gs.spec_3, gs.spec_4, gs.stock, gs.price')
                ->alias('gs')
                ->join('LEFT JOIN ' . C('DB_PREFIX') . 'goods g ON g.goods_id = gs.goods_id')
                ->where('spec_id=' . $spec_id)
                ->find();

        if (!$spec_info) {
            render('10300', '此商品不存在');
            /* 商品不存在 */
        }

        /* 如果是自己店铺的商品，则不能购买 */
        if ($this->_user_id) {
            if ($spec_info['store_id'] == $this->_user_id) {
                render('10402', '不能购买自己的商品!');
            }
        }

        if ($quantity > $spec_info['stock']) {
            render('10301', '没有足够的商品');
        }

        /* 商品是否添加过 */
        $item_info = $this->_Cart_mod->where('spec_id=' . $spec_id . ' AND user_id=' . $this->_user_id)->find();
        if (!empty($item_info)) {

            //如果是团购商品则判断是否限购
            if ($item_info['goods_type'] == GOODS_TYPE_GROUP) {
                $max_per_user = M('ju')->where('status=1 AND goods_id=' . $item_info['goods_id'])->getField('max_per_user');
                if ($max_per_user) {
                    //检查数量是否超过限定团购数量
                    $ordergoods_quantity = intval(M('OrderGoods')->where("order_alias.status<>" . ORDER_CANCELED . " AND order_alias.buyer_id=" . $this->_user_id . " AND promotions_id=" . $item_info['promotions_id'] . " AND goods_type=" . GOODS_TYPE_GROUP . " AND spec_id=" . $spec_id)->alias('ordergoods')->join('LEFT JOIN ' . C('DB_PREFIX') . 'order order_alias  ON order_alias.order_id=ordergoods.order_id')->sum('quantity'));
                    //购物车中相同商品不同规格的商品
                    $same_goods = intval(M('Cart')->where('goods_id=' . $item_info['goods_id'])->sum('quantity'));
                    if (($ordergoods_quantity + $quantity + $same_goods) > $max_per_user) {
                        render('10407', '特卖特价商品，每人限购' . $max_per_user . '件');
                    }
                }
            }

            $this->_Cart_mod->where('spec_id=' . $spec_id . ' AND user_id=' . $this->_user_id)->setInc('quantity');
//            render('10403', '商品已经加入购物车');
        } else {
            $spec_1 = $spec_info['spec_name_1'] ? $spec_info['spec_name_1'] . ':' . '<img src="' . str_replace('goodsspec/', 'goodsspec/spec_', $spec_info['spec_1']) . '">' : $spec_info['spec_1'];
            $spec_2 = $spec_info['spec_name_2'] ? $spec_info['spec_name_2'] . ':' . $spec_info['spec_2'] : $spec_info['spec_2'];
            $spec_3 = $spec_info['spec_name_3'] ? $spec_info['spec_name_3'] . ':' . $spec_info['spec_3'] : $spec_info['spec_3'];
            $spec_4 = $spec_info['spec_name_4'] ? $spec_info['spec_name_4'] . ':' . $spec_info['spec_4'] : $spec_info['spec_4'];

            $specification = $spec_1 . ' ' . $spec_2 . ' ' . $spec_3 . ' ' . $spec_4;

            //当用多个促销条件存在时候， 此方法用来处理具体使用哪一个价格
            $spec_info = D('cart')->get_spec_price($spec_info, $this->_user_id, $promotions_id);

            //如果是团购商品则判断是否限购
            if ($spec_info['goods_type'] == GOODS_TYPE_GROUP) {
                if ($spec_info['max_per_user']) {
                    //检查数量是否超过限定团购数量
                    $ordergoods_quantity = intval(M('OrderGoods')->where("order_alias.status<>" . ORDER_CANCELED . " AND order_alias.buyer_id=" . $this->_user_id . " AND promotions_id=" . $promotions_id . " AND goods_type=" . GOODS_TYPE_GROUP . " AND spec_id=" . $spec_id)->alias('ordergoods')->join('LEFT JOIN ' . C('DB_PREFIX') . 'order order_alias  ON order_alias.order_id=ordergoods.order_id')->sum('quantity'));
                    //购物车中相同商品不同规格的商品
                    $same_goods = intval(M('Cart')->where('goods_id=' . $spec_info['goods_id'])->sum('quantity'));
                    if (($ordergoods_quantity + $quantity + $same_goods) > $spec_info['max_per_user']) {
                        render('10407', '特卖特价商品，每人限购' . $spec_info['max_per_user'] . '件');
                    }
                }
            }

            /* 将商品加入购物车 */
            $cart_item = array(
                'user_id' => $this->_user_id,
                'session_id' => $this->_user_id,
                'store_id' => $spec_info['store_id'],
                'spec_id' => $spec_id,
                'goods_id' => $spec_info['goods_id'],
                'goods_name' => addslashes($spec_info['goods_name']),
                'specification' => addslashes(trim($specification)),
                'price' => $spec_info['price'],
                'quantity' => $quantity,
                'goods_image' => addslashes($spec_info['default_image']),
                'promotions_id' => empty($spec_info['promotions_id']) ? 0 : $spec_info['promotions_id'],
                'goods_old_price' => $spec_info['goods_old_price'],
                'goods_type' => $spec_info['goods_type'],
            );
            /* 添加并返回购物车统计即可 */
            $this->_Cart_mod->data($cart_item)->add();
        }

        $cart_status = $this->_get_cart_status();
        render('10000', '', $cart_status);
    }

    /**
     * @api {get} /index.php?m=Home&c=Goods&a=update  更新购物车
     * 
     * @apiName 更新购物车
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 更新购物车
     * 
     * @apiParam {String} spec_id 规格ID
     * @apiParam {String} quantity 数量
     */
    function update() {
        $spec_id = I('request.spec_id', 0);
        $quantity = I('request.quantity', 0);

        if (!$spec_id || !$quantity) {
            render('10001', '缺少参数');
        }

        /* 是否有商品 */
        $Goodsspec_mod = M('goods_spec');
        $spec_info = $Goodsspec_mod
                ->field('g.store_id, g.if_open, g.goods_id, g.goods_name, g.spec_name_1, g.spec_name_2, g.spec_name_3, g.spec_name_4, g.default_image, gs.spec_1, gs.spec_2, gs.spec_3, gs.spec_4, gs.stock, gs.price')
                ->alias('gs')
                ->join('LEFT JOIN ' . C('DB_PREFIX') . 'goods g ON g.goods_id = gs.goods_id')
                ->where('spec_id=' . $spec_id)
                ->find();

        if (!$spec_info) {
            render('10300', '此商品不存在');
            /* 商品不存在 */
        }

        if ($quantity > $spec_info['stock']) {
            render('10301', '没有足够的商品');
        }

        /* 获取购物车中的信息，用于获取价格并计算小计 */
        $item_info = $this->_Cart_mod->where('spec_id=' . $spec_id . ' AND user_id=' . $this->_user_id)->find();
        if (empty($item_info)) {
            render('10404', '商品未加入购物车');
        }

        //如果是团购商品则判断是否限购
        if ($item_info['goods_type'] == GOODS_TYPE_GROUP) {
            $max_per_user = M('ju')->where('status=1 AND goods_id=' . $item_info['goods_id'])->getField('max_per_user');
            if ($max_per_user) {
                //检查数量是否超过限定团购数量
                $ordergoods_quantity = intval(M('OrderGoods')->where("order_alias.status<>" . ORDER_CANCELED . " AND order_alias.buyer_id=" . $this->_user_id . " AND promotions_id=" . $item_info['promotions_id'] . " AND goods_type=" . GOODS_TYPE_GROUP . " AND spec_id=" . $spec_id)->alias('ordergoods')->join('LEFT JOIN ' . C('DB_PREFIX') . 'order order_alias  ON order_alias.order_id=ordergoods.order_id')->sum('quantity'));
                //购物车中相同商品不同规格的商品
                $same_goods = intval(M('Cart')->where('goods_id=' . $item_info['goods_id'])->sum('quantity'));
                if (($ordergoods_quantity + $quantity + $same_goods) > $max_per_user) {
                    render('10407', '特卖特价商品，每人限购' . $max_per_user . '件');
                }
            }
        }


        /* 修改数量 */
        $this->_Cart_mod->where('spec_id=' . $spec_id . ' AND user_id=' . $this->_user_id)->save(array('quantity' => $quantity,));

        $cart_status = $this->_get_cart_status();
        render('10000', '', $cart_status);
    }

    function _get_cart_status() {
        /* 默认的返回格式 */
        $data = array(
            'status' => array(
                'quantity' => 0, //总数量
                'amount' => 0, //总金额
                'kinds' => 0, //总种类
            ),
            'carts' => array(), //购物车列表，包含每个购物车的状态
        );

        /* 获取所有购物车 */
        $carts = $this->_get_carts();
        if (empty($carts)) {
            return $data;
        }
        $data['carts'] = array_values($carts);
        foreach ($carts as $store_id => $cart) {
            $data['status']['quantity'] += $cart['quantity'];
            $data['status']['amount'] += $cart['amount'];
            $data['status']['kinds'] += $cart['kinds'];
        }

        return $data;
    }

    function _get_carts($store_id = 0) {
        $store_id = I('request.store_id', 0);
        
        $carts = D('cart')->get_goods($store_id, $this->_user_id);
        return $carts;
    }

}
